/******************************************************************************
 * * hal_md5hl.c
 *
 * *(C) Copyright 2021 Asr International Ltd.
 * * All Rights Reserved
 * ******************************************************************************/

#include <stdio.h>
#include <stdlib.h>

#define LENGTH  16

#include "hal_md5.h"

char *MD5End(MD5_CTX *ctx, char *buf)
{
  int i;
  unsigned char digest[LENGTH];
  static const char hex[] = "0123456789abcdef";

  if (!buf)
    buf = malloc(2 * LENGTH + 1);
  if (!buf)
    return 0;
  MD5Final(digest, ctx);
  for (i = 0; i < LENGTH; i++) {
    buf[i + i] = hex[digest[i] >> 4];
    buf[i + i + 1] = hex[digest[i] & 0x0f];
  }
  buf[i + i] = '\0';
  return buf;
}

char *MD5Data(const void *data, unsigned int len, char *buf)
{
  MD5_CTX ctx;

  MD5Init(&ctx);
  MD5Update(&ctx, (unsigned char *)data, len);
  return (MD5End(&ctx, buf));
}

void md5_binary(const void *data, unsigned int len, unsigned char digest[16])
{
  MD5_CTX ctx;

  MD5Init(&ctx);
  MD5Update(&ctx, (unsigned char *)data, len);
  MD5Final(digest, &ctx);
}
